package jee.boot.module.sms.sender;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import jee.boot.module.sms.config.AliSmsConfig;
import jee.boot.entity.sms.Sms;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 阿里云短信发送器
 */
public class AliSmsSender implements ISmsSender {
    private Logger logger = LoggerFactory.getLogger(AliSmsSender.class);
    private AliSmsConfig config;

    public AliSmsSender(AliSmsConfig config) {
        this.config = config;
    }

    @Override
    public void send(Sms entity) throws Exception {
        Client client = createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(entity.getPhoneNumber())
                .setSignName(entity.getSignName())
                .setTemplateCode(entity.getTemplateCode())
                .setTemplateParam(entity.getTemplateParam());
        SendSmsResponse response = client.sendSms(sendSmsRequest);
        SendSmsResponseBody body = response.getBody();
        entity.setMessage(body.getMessage());
        entity.setBizId(body.getBizId());
        entity.setCode(body.getCode());
        entity.setRequestId(body.getRequestId());
        if ("OK".equals(entity.getCode())) {
            entity.setSendStatus("Y");
        } else {
            entity.setSendStatus("N");
        }
    }

    public Client createClient() throws Exception {
        Config c = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(config.getAccessKeyId())
                // 您的AccessKey Secret
                .setAccessKeySecret(config.getAccessKeySecret());
        // 访问的域名
        c.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(c);
    }
}
